const { getLoginUserInfo, updateUserInfo, sendEmailVerifyCode } = require('../../utils/info');
const { decryptPhone } = require('../../utils/miniapp');
const { getPhoneQuota } = require('../../utils/quota');
const app = getApp();
let that;
Page({
  data: {
    userInfo: {},
    genderOptions: [{label: "保密", value: "2"}, {label: "男", value: "0"}, {label: "女", value: "1"}],
    genderIndex: 0,
    today: '',
    fileBase64: '',
    canGetPhone: false,
    phoneError: '',
    emailError: '',
    emailCode: '',
    emailCodeSent: false,
    emailCodeCountdown: 0,
    emailCodeError: '',
    canSubmit: false,
    // 原始的电子邮件
    oldEmail: '',
  },
  onLoad() {
    that = this;
    // 获取今天日期
    const today = this.formatDate(new Date());
    this.setData({ today });
    // 加载配额
    this.loadQuota();
    this.loadUserInfo();
    this.updateCanSubmit();
  },
  formatDate(date) {
    const y = date.getFullYear();
    const m = (date.getMonth() + 1).toString().padStart(2, '0');
    const d = date.getDate().toString().padStart(2, '0');
    return `${y}-${m}-${d}`;
  },
  loadUserInfo() {
    getLoginUserInfo().then(res => {
      const userInfo = res.data || res || {};
      const genderIndex = this.data.genderOptions.findIndex(opt => String(opt.value) === String(userInfo.sex));
      this.setData({
        userInfo,
        genderIndex: genderIndex === -1 ? 0 : genderIndex,
        oldEmail: userInfo.email
      }, () => {
        this.updateEmailCodeUI();
      });
    });
  },
  onChooseAvatar() {
    const fs = wx.getFileSystemManager();
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const file = res.tempFiles[0];
        // 检查文件大小，2MB = 2 * 1024 * 1024 = 2097152 bytes
        const maxSize = 2 * 1024 * 1024; // 2MB
        if (file.size > maxSize) {
          wx.showToast({ 
            title: '文件大小不能超过2MB', 
            icon: 'none',
            duration: 2000
          });
          return;
        }
        
        // 读取临时文件 base64字符串
        fs.readFile({
          filePath: file.path, // 第一个文件的路径
          encoding: 'base64', // 或者使用 'binary' 来获取二进制数据
          success(res) {
            that.setData({
              fileBase64: res.data,
              'userInfo.avatar': file.path // 立即回显本地图片
            });
          },
          fail(err) {
            console.error("读取文件失败:", err);
            wx.showToast({ 
              title: '读取文件失败', 
              icon: 'none' 
            });
          }
        });
      }
    });
  },
  onGenderChange(e) {
    const genderIndex = e.detail.value;
    const sexValue = this.data.genderOptions[genderIndex].value;
    this.setData({ genderIndex, 'userInfo.sex': sexValue });
  },
  // 手机号输入
  onPhoneInput(e) {
    this.setData({ 
      'userInfo.phoneNumber': e.detail.value,
      phoneError: ''
    }, this.updateCanSubmit);
  },
  // 手机号失焦验证
  onPhoneBlur(e) {
    const phoneNumber = e.detail.value;
    if (phoneNumber && !this.validatePhone(phoneNumber)) {
      this.setData({ phoneError: '请输入正确的手机号码' });
    } else {
      this.setData({ phoneError: '' });
    }
  },
  // 邮箱输入
  onEmailInput(e) {
    const email = e.detail.value;
    this.setData({
      'userInfo.email': email,
      emailError: ''
    }, this.updateCanSubmit);
  },
  // 邮箱失焦验证
  onEmailBlur(e) {
    const email = e.detail.value;
    if (email && !this.validateEmail(email)) {
      this.setData({ emailError: '请输入正确的邮箱地址' }, this.updateCanSubmit);
    } else {
      this.setData({ emailError: '' }, this.updateCanSubmit);
    }
    this.updateEmailCodeUI();
  },
  // 验证手机号码
  validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },
  // 验证邮箱
  validateEmail(email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  },

  /**
   * 加载配额
   */
  loadQuota(){
    // 先查配额
    getPhoneQuota().then(res => {
      // 设置是否可以
      that.setData({
        canGetPhone: (res.leftQuota || 0) > 0
      });
    }).catch(() => {
      wx.showToast({ title: '配额查询失败', icon: 'none' });
    });
  },
  // 微信授权获取手机号
  onGetWeChatPhone(e) {

    // 有配额才继续
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv, code } = e.detail;
      // 获取sessionKey，通常在登录时已获取
      const sessionKey = wx.getStorageSync('sessionKey');
      if (!sessionKey) {
        wx.showToast({ title: '请重新登录', icon: 'none' });
        return;
      }
      wx.showLoading({ title: '获取中...' });
      decryptPhone(encryptedData, iv, sessionKey, code).then(res => {
        wx.hideLoading();
        if (res && res.phoneNumber) {
          this.setData({ 
            'userInfo.phoneNumber': res.phoneNumber,
            canGetPhone: (res.leftQuota || 0) > 0,
            phoneError: '' // 清除错误提示
           });
          wx.showToast({ title: '获取成功', icon: 'success' });
        } else {
          wx.showToast({ title: '获取失败', icon: 'none' });
        }
      }).catch(() => {
        wx.hideLoading();
        wx.showToast({ title: '获取失败', icon: 'none' });
      });
    } else {
      wx.showToast({ title: '未授权', icon: 'none' });
    }
  },
  // 昵称输入
  onNickNameInput(e) {
    this.setData({ 'userInfo.nickName': e.detail.value }, this.updateCanSubmit);
  },
  updateEmailCodeUI() {
    const { userInfo, emailCodeSent } = this.data;
    const validEmail = this.validateEmail(userInfo.email);
    this.setData({
      showSendCodeBtn: !!(validEmail && !emailCodeSent),
      showEmailCodeInput: !!(validEmail && emailCodeSent)
    });
  },
  onSendEmailCode() {
    const { userInfo, emailCodeSent } = this.data;
    if (emailCodeSent) return;
    if (!this.validateEmail(userInfo.email)) {
      this.setData({ emailError: '请输入正确的邮箱地址' });
      return;
    }
    wx.showLoading({ title: '发送中...', mask: true });
    sendEmailVerifyCode(userInfo.email).then(res => {
      wx.hideLoading();
      wx.showToast({ title: '验证码已发送', icon: 'success' });
      this.setData({
        emailCodeSent: true,
        emailCodeCountdown: res,
        emailCodeError: ''
      }, () => {
        this.startEmailCodeCountdown();
      });
    }).catch((e) => {
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '发送失败，请稍后重试', icon: 'none' });
    });
  },
  startEmailCodeCountdown() {
    if (this.data.emailCodeCountdown > 0) {
      this.emailCodeTimer = setTimeout(() => {
        this.setData({ emailCodeCountdown: this.data.emailCodeCountdown - 1 }, () => {
          this.startEmailCodeCountdown();
        });
      }, 1000);
    } else {
      this.setData({ emailCodeSent: false, emailCode: '' });
    }
  },
  onEmailCodeInput(e) {
    this.setData({ emailCode: e.detail.value, emailCodeError: '' }, this.updateCanSubmit);
  },
  onUnload() {
    if (this.emailCodeTimer) clearTimeout(this.emailCodeTimer);
  },
  onSubmit(e) {
    const { userInfo, fileBase64, phoneError, emailError, emailCodeSent, emailCode, oldEmail } = this.data;
    
    // 验证手机号码
    if (userInfo.phoneNumber && !this.validatePhone(userInfo.phoneNumber)) {
      this.setData({ phoneError: '请输入正确的手机号码' });
      return;
    }
    
    // 验证邮箱
    if (userInfo.email && !this.validateEmail(userInfo.email)) {
      this.setData({ emailError: '请输入正确的邮箱地址' });
      return;
    }
    
    // 判断用户是否输入新的电子邮箱
    // 存在旧的，但是跟新的
    // 只要没有旧的，现在新增，那就需要验证码
    if ((oldEmail && userInfo.email && oldEmail !== userInfo.email)
    || (!oldEmail && userInfo.email)) {
      if (!emailCode){
        this.setData({ emailCodeError: '请先发送验证码' });
        return
      }
    }
    // 邮箱验证码校验：只有用户主动输入邮箱且发送过验证码时才校验
    if (emailCodeSent) {
      if (!emailCode || emailCode.length !== 6) {
        this.setData({ emailCodeError: '请输入6位验证码' });
        return;
      }
      // 这里可以加上验证码校验逻辑
    }
    
    // 如果有错误提示，不允许提交
    if (phoneError || emailError) {
      return;
    }
    
    wx.showLoading({ title: '保存中...' });
    updateUserInfo({
      avatarBase64: fileBase64,
      sex: userInfo.sex,
      nickName: userInfo.nickName,
      phoneNumber: userInfo.phoneNumber,
      email: userInfo.email,
      emailVerifyCode: emailCode
    }).then((res) => {
      if (res) {
        wx.setStorageSync('userInfo', res);
      }
      wx.hideLoading();
      wx.showToast({ title: '保存成功', icon: 'success' });
      setTimeout(() => wx.navigateBack(), 800);
    }).catch((e) => {
      wx.hideLoading();
      wx.showToast({ title:  (e && e.data && e.data.msg) || '发送失败，请稍后重试', icon: 'none' });
    });
  },
  updateCanSubmit() {
    const { userInfo, phoneError, emailError, emailCodeSent, emailCode, emailCodeError } = this.data;
    let canSubmit = true;
    // 昵称必填
    if (!userInfo.nickName || userInfo.nickName.length === 0) canSubmit = false;
    // 手机号必填且格式正确
    if (!userInfo.phoneNumber || !this.validatePhone(userInfo.phoneNumber)) canSubmit = false;
    if (phoneError) canSubmit = false;
    // 邮箱必填且格式正确
    if (!userInfo.email || !this.validateEmail(userInfo.email)) canSubmit = false;
    if (emailError) canSubmit = false;
    // 如果已发送验证码，验证码必填且为6位
    if (emailCodeSent && (!emailCode || emailCode.length !== 6)) canSubmit = false;
    if (emailCodeError) canSubmit = false;
    this.setData({ canSubmit });
  }
}); 